import datetime
import tornado.httpserver #tornado 服务
import tornado.httpclient #模拟用户的请求
import tornado.web
import tornado.ioloop
from tornado.options import define,options,parse_command_line


define('port',default=8080,help='如果命令行没有端口参数就用默认',type=int)

class IndexHandler(tornado.web.RequestHandler):
    def get(self,*args,**kwargs):
        q = self.get_argument('q')
        #模拟用户的请求  创建一个客户端
        client = tornado.httpclient.HTTPClient()
        response = client.fetch("https://cn.bing.com/search?q={}".format(q))
        #同步在这里必须是等待   等待返回之后再进行下一个  所以很慢

        body = response.body #返回的源代码
        now = datetime.datetime.utcnow()
        self.write(
        """
            <div style='text-align:center'>
                <div style='font-size:18px'>
                    %s
                </div>
                <div style='font-size:30px'>
                    %s
                </div>
            </div>
        """ % (q,body))


def make_app():
    return tornado.web.Application(handlers=[
        (r'/',IndexHandler)

    ],autoreload=True)

if __name__ == "__main__":
    parse_command_line()
    app = make_app()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
